<template>
  <div>
    <div class="navbar-div">
      <van-nav-bar title="类别列表" /> 
    </div>
    <div>
      <van-row>
        <van-col span="6">
          <div id="leftNav">
            <ul>
              <li @click="clickCategory(index, item.ID)" :class="{'categoryActive': categoryFirstIndex===index}" v-for="(item, index) of categoryFirst" :key="index">{{item.MALL_CATEGORY_NAME}}</li>
            </ul>
          </div>
        </van-col>
        <van-col span="18">
          <div class="tabCategorySub">
            <van-tabs v-model="active" title-active-color="red" @click.native="onClickCategorySub(categorySub[active].ID)">
              <van-tab v-for="(item, index) in categorySub" :key="index" :title="item.MALL_SUB_NAME"></van-tab>
            </van-tabs>
            <div id="list-div">
              <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
                <van-list
                  v-model="loading"
                  :finished="finished"
                  finished-text="没有更多了"
                  :offset="50"
                  @load="onLoad"
                >
                  <div class="list-item" @click="goGoodsInfo(item.ID)" v-for="(item, index) in goodsList" :key="index">
                    <div class="list-item-img"><img :src="item.IMAGE1" :onerror="errorImg" width="100%" /></div>
                    <div class="list-item-text">
                      <div>{{item.NAME}}</div>
                      <div class="">{{item.ORI_PRICE | moneyFilter}}</div>
                    </div>
                  </div>
                </van-list>
              </van-pull-refresh>

            </div>
        </div>
        </van-col>
      </van-row>
    </div>
  </div>
</template>

<script>
import axios from '@/axios/axios.js';
import toMoney from '@/filters/moneyFilter.js'
export default {
  name: 'CategoryList',
  data() {
    return {
      categoryFirst: [],    // 商品1级分类数组
      categoryFirstIndex: 0,    // 1级商品分类组中，被点击的那一项的索引
      categorySub: [],    // 商品2级分类数组
      active: 0,    // 商品2级分类被点击的tab的索引
      loading: false,   // 商品栏是否处于上拉加载的状态
      finished: false,   // 商品栏中的商品是否都已经加载完毕了
      list: [],   // 商品栏的商品数组
      refreshing: false,    // 控制商品栏是否处于下拉刷新状态

      page: 1,    // 商品列表的页数。没上拉加载都会多出10条商品数据
      categorySubId: '',    // 当前选中的商品2级分类的ID
      goodsList: [],    // 商品列表
      errorImg: 'this.src="'+require('@/assets/img/errorimg.png')+'"'
    }
  },
  filters: {
    moneyFilter(money) {
      return '￥ ' + toMoney(money) + '元';
    }
  },
  created(){
    this.getCategory();
  },
  activated() {
    let mallCategoryId = this.$route.params.mallCategoryId;
    for (let i=0, len=this.categoryFirst.length; i<len; i++) {
      if (this.categoryFirst[i].ID==mallCategoryId) {
        this.categoryFirstIndex=i;
        break;
      }
    }
  },
  mounted() {
    let winHeight = document.documentElement.clientHeight;
    document.getElementById('leftNav').style.height = winHeight - 46-50 + 'px';
    document.getElementById('list-div').style.height = winHeight - 90-50 + 'px';
    
  },
  methods: {
    // 页面加载时，获取商品的1级分类
    getCategory() {
      axios.ajax({
        url: this.$url.category.getCategoryList,
        method: 'GET',
      })
      .then(res=>{
        console.log("getCategoryList", res)
        if(res.message){
          this.categoryFirst = res.message;
          this.getCategorySubByCategoryId(this.categoryFirst[0].ID)
        }
      })
      .catch(error=>{
        this.$toast('error! 数据取得失败')
      }) 
    },
    // 1级商品分类组中，选中项改变时的事件。
    async clickCategory(index, categoryId) {
      this.categoryFirstIndex = index;
      this.page=1
      this.finished = false;
      this.goodsList=[]
      await this.getCategorySubByCategoryId(categoryId);
      this.categorySubId = this.categorySub[0].ID
      this.getGoodList();
    },
    // 2级商品分类中的项，被点击时的事件
    onClickCategorySub(categorySubId) {
      this.categorySubId = categorySubId;
      this.goodsList=[]
      this.finished = false
      this.page=1
      this.getGoodList();
    },
    //根据1级商品分类ID读取2级商品分类列表
    async getCategorySubByCategoryId(categoryId){
      await axios.ajax({
        url: this.$url.category.getCategorySubList,
        method:'POST',
        data:{categoryId:categoryId}
      })
      .then(res=>{
          if(res.message ){
            this.categorySub=res.message;
            this.active = 0;
          }else{
            this.$toast('出错了，数据取得失败')
          }  
      })
    },
    // 上拉加载事件
    onLoad() {
      // console.log('onLoad')
      setTimeout(() => {
        this.categorySubId = this.categorySubId?this.categorySubId:this.categorySub[0].ID;
        this.getGoodList();
      }, 500)
    },
    // 下拉刷新事件
    onRefresh() {
      setTimeout(() => {
        this.refreshing = false;
        this.finished = false;    // 因为list又被清空了，所以每次下拉刷新后，要恢复上拉加载商品的功能。
        this.goodsList = [];
        this.page=1
        this.onLoad();    // 下拉刷新后，给list赋10个变量的初始值
      }, 500);
    },
    // 获取商品列表
    getGoodList() {
      axios.ajax({
        method: 'POST',
        url: this.$url.category.getGoodsListByCategorySubID,
        data: {page:this.page, categorySubId:this.categorySubId},
      }).then(res => {
        // console.log('getGoodList', res.message)
        if (res.message.length) {
          this.page++;
          this.goodsList = this.goodsList.concat(res.message);
        } else {
          this.finished = true;
        }
        this.loading=false;
      })
    },
    // 跳转到商品详情页
    goGoodsInfo(goodsId) {
      this.$router.push({name:'Goods',params:{goodsId:goodsId}})
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/common.styl';
.navbar-div {
  /deep/ .van-nav-bar {
    background-color: $colorC;
  }
  /deep/ .van-nav-bar__title {
    font-weight: bold;
  }
}
#leftNav {    // 左侧商品1级分类
  background-color: aliceblue;
  ul {
    li {
      line-height: 2rem;
      border-bottom:1px solid #E4E7ED;
      padding:3px;
      font-size:0.8rem;
      text-align: center;
    }
  }
}
.tabCategorySub {   // 右侧2级分类和商品
  /deep/ .van-tab {
    border-right: 1px solid rgba(0,0,0,.1);
  }
  /deep/ .van-tab--active {
    background-color: $colorC;
  }
  .list-item{
    display: flex;
    flex-direction: row;
    font-size:0.8rem;
    border-bottom: 1px solid #f0f0f0;
    background-color: #fff;
    padding: .3125rem;
    .list-item-img {
      flex: 1;
    }
    .list-item-text {
      flex: 2;
      margin-top: .625rem;
      margin-left: .625rem;
    }
  }
  #list-div {
    overflow: scroll;
  }
}
.categoryActive{    // 1级商品分类每一项被点击时的高亮颜色
  background-color: skyblue;
}
</style>